#include <sstream>
#include <SypX/Font.h>

#ifdef SYPX_MEMCHECK
#include "mmgr.h"
#endif

#include "MenuScene.h"
#include "TutorialScene.h"
#include "SheepDefenceApp.h"
#include "MoveSeg.h"

namespace SheepDefence
{
	TutorialScene::TutorialScene(SypX::Font* f):font(f),cumTime(0),counter(0),fps(0)
	{

	}

	TutorialScene::~TutorialScene(void)
	{
		delete level;
	}

	void TutorialScene::init()
	{
		engine = SypX::Engine::getSingleton();
		render = engine->getRenderer();
		canvas = engine->getCanvas();
		render->setClearScreenColor(SypX::Vec4(0.0f,0.0f,0.0f,1.0f));		

		if(!font)
		{
			font = engine->loadFontFromFile("Fonts/sheepFont.ttf", 24, 3);
		}

		level = new MoveSeg(font, this);

		mouseDown = false;

	}

	void TutorialScene::run()
	{
		float time;
		
		render->clearScreen();
		handleInput();

		time = canvas->getElapsedTime();
		cumTime += time;

		if (level->state == WIN)
			changeScene(new MenuScene(font));
		
		render->setActiveColor(SypX::Vec4(1.0f,1.0f,1.0f,1.0f));
		level->draw();
		level->act(time);
		level->advance(time);
		calcAndDrawFPS();
		canvas->swapBuffers();

	}

	void TutorialScene::calcAndDrawFPS()
	{
		++counter;
		if(cumTime > 1.0f)
		{
			fps = counter;
			cumTime = 0;
			counter = 0;			
		}
		
		std::ostringstream oss;
		oss << fps << " FPS";		
		font->drawText(oss.str(), 10.0f, 430.0f, 1.0f);
		render->setActiveColor(SypX::Vec4(1.0f,1.0f,1.0f, 0.85f));
		font->drawBufferedInstances();
	}

	void TutorialScene::handleInput()
	{
		SypX::Event e, nextEvent = SypX::Event();
		nextEvent.type = SypX::NOEVENTS;
		bool breakOut = false;

		while (true)
		{
			if (nextEvent.type == SypX::NOEVENTS)
				e = canvas->getEvent();
			else
			{
				e = nextEvent;
				nextEvent.type = SypX::NOEVENTS;
			}

			switch (e.type) 
			{
			case SypX::TOUCHDOWN:
			case SypX::MOUSELEFTDOWN:
				level->move((float) e.location.x, (float) e.location.y);				
				mouseDown = true;
				if (breakOut) return;
				break;
			case SypX::TOUCHUP:
			case SypX::MOUSELEFTUP:
				mouseDown = false;
				if (breakOut) return;
				break;
			case SypX::TOUCHMOVE:
			case SypX::MOUSEMOVE:
				if (mouseDown)
				{
					nextEvent = canvas->getEvent();
					while (nextEvent.type == SypX::MOUSEMOVE || nextEvent.type == SypX::TOUCHMOVE)
					{
						e = nextEvent;
						nextEvent = canvas->getEvent();
					}

					level->move((float) e.moved.curr.x, (float) e.moved.curr.y);
					if (breakOut) return;
					breakOut = true;
				}
				break;
			case SypX::NOEVENTS:
				return;
			default:
				break;
			}
		}

	}

}